/**
 * 
 */
package server.internal;

import static commons.Preconditions.checkNotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import server.AttributesStorer;

import commons.FileAttributes;
import commons.exception.AlreadyUsedNameException;
import commons.exception.NotFoundNameException;

/**
 * @author armstrong
 * 
 */
public class DefaultAttributesStorer implements AttributesStorer {

	private final Map<String, FileAttributes>	attributes;

	public DefaultAttributesStorer(final Map<String, FileAttributes> attributes) {

		checkNotNull("attributes cannot be null.", attributes);

		this.attributes = attributes;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#delete(java.lang.String)
	 */
	@Override
	public void delete(final String name) throws NotFoundNameException {

		checkNotNull("name cannot be null.", name);

		if (!attributes.containsKey(name)) {
			throw new NotFoundNameException("name not found: " + name);
		}

		attributes.remove(name);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#exist(java.lang.String)
	 */
	@Override
	public boolean exist(final String name) {
		checkNotNull("name cannot be null.", name);
		return attributes.containsKey(name);
	}

	// FIXME test it
	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#list()
	 */
	@Override
	public List<String> list() {
		return new ArrayList<String>(attributes.keySet());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#map(java.lang.String, java.lang.Object)
	 */
	@Override
	public void map(final String name, final FileAttributes object)
			throws AlreadyUsedNameException {

		checkNotNull("name cannot be null.", name);
		checkNotNull("object cannot be null.", object);

		if (attributes.containsKey(name)) {
			throw new AlreadyUsedNameException("name already used:" + name);
		}

		attributes.put(name, object);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see commons.NameResolver#resolve(java.lang.String)
	 */
	@Override
	public FileAttributes resolve(final String name)
			throws NotFoundNameException {

		checkNotNull("name cannot be null.", name);

		if (!attributes.containsKey(name)) {
			throw new NotFoundNameException("name not found: " + name);
		}

		return attributes.get(name);
	}
}
